import createDomELement from './createDomELement'
import mountElement from './mountElement'
import updateNodeElement from './updateNodeElement'
import updateTextNode from './updateTextNode'
import unmountNode from './unmountNode'
import diffComponent from './diffComponent'
export default function diff (virtualDom , container, oldDom) {
  const oldVirtualDom = oldDom && oldDom._virtualDom
  const oldComponent = oldVirtualDom && oldVirtualDom.component
  if (!oldDom) {// 没有旧节点直接绑定新节点
    mountElement(virtualDom, container)
  } else if (virtualDom.type !== oldVirtualDom.type && typeof virtualDom.type !== 'function') { //当新旧节点类型不一样时，直接替换 
    const newElement = createDomELement(virtualDom)
    oldDom.parentNode.replaceChild(newElement, oldDom)
  } else if (typeof virtualDom.type === 'function') {// 组件更新
    diffComponent(virtualDom, oldComponent, oldDom, container)
  } else if (oldVirtualDom && virtualDom.type === oldVirtualDom.type) {
    if (virtualDom.type === 'text') {
      // 更新内容
      updateTextNode(virtualDom, oldVirtualDom, oldDom)
    } else {// 更新元素节点
      updateNodeElement(oldDom, virtualDom, oldVirtualDom)
    }
    virtualDom.children.forEach((child, index) => {
      diff(child, oldDom, oldDom.childNodes[index])
    });
    // 删除节点
    let oldChildNods = oldDom.childNodes
    // 判断旧节点的数量
    if (oldChildNods.length >virtualDom.children.length) {
      for(let i = oldChildNods.length -1; i > virtualDom.children.length -1; i--) {
        unmountNode(oldChildNods[i])
      }
    }
  }
}